package com.uw.uwconfig.client.config;

import com.uw.uwconfig.client.contant.PropertyNameConstant;
import com.uw.uwconfig.client.repository.UwRepository;
import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;

import java.util.Map;

@Setter
public class PropertySourcesBeanFactoryPostProcessor implements BeanFactoryPostProcessor, ApplicationContextAware, EnvironmentAware, PriorityOrdered {

    private Environment environment;
    private ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ConfigurableEnvironment ENV = (ConfigurableEnvironment) environment;

        if (ENV.getPropertySources().contains(PropertyNameConstant.UW_PROPERTY_SOURCES)) {
            return;
        }

        // 获取远端 config server 的配置
        String app = ENV.getProperty("uw.config.app", "app1");
        String env = ENV.getProperty("uw.config.env", "dev");
        String namespace = ENV.getProperty("uw.config.namespace", "public");
        String serverAddress = ENV.getProperty("uw.config.serverAddress", "http://localhost:9129");
        ConfigServerMeta configServerMeta = new ConfigServerMeta(app, env, namespace, serverAddress);
        UwRepository uwRepository = UwRepository.getDefault(environment, applicationContext);
        Map<String, Object> propertyMap = uwRepository.getConfig(configServerMeta);

        // 启动配置监控。
        ConfigVersionChecker versionChecker = new ConfigVersionChecker(configServerMeta, uwRepository);
        versionChecker.start();

        MapPropertySource mapPropertySource = new MapPropertySource(PropertyNameConstant.UW_PROPERTY_SOURCE, propertyMap);

        CompositePropertySource compositePropertySource = new CompositePropertySource(PropertyNameConstant.UW_PROPERTY_SOURCES);
        compositePropertySource.addPropertySource(mapPropertySource);
        ENV.getPropertySources().addFirst(compositePropertySource);
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
